import React, { useState, useMemo } from 'react';
import {
    Dialog,
    DialogTitle,
    DialogContent,
    DialogActions,
    Button,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    Paper,
    FormControl,
    InputLabel,
    Select,
    MenuItem,
    Box,
    TablePagination,
    TextField,
    TableSortLabel,
    LinearProgress,
    InputAdornment,
    Grid,
    Snackbar,
    Alert
} from '@mui/material';
import { Search as SearchIcon } from '@mui/icons-material';
import { configurationApi } from '../services/api';

// 将格式化函数移到组件外部
const formatValue = (value, type, format) => {
    if (value == null || value === '') return '-';
    
    switch (type) {
        case 'date':
            try {
                const date = new Date(value);
                return format ? 
                    new Intl.DateTimeFormat('zh-CN', getDateFormatOptions(format)).format(date) : 
                    date.toLocaleString('zh-CN');
            } catch (e) {
                return value;
            }
        case 'number':
            try {
                const num = Number(value);
                return format ? 
                    num.toLocaleString('zh-CN', getNumberFormatOptions(format)) : 
                    num.toLocaleString('zh-CN');
            } catch (e) {
                return value;
            }
        case 'phone':
            return formatPhoneNumber(value);
        default:
            return value;
    }
};

const formatPhoneNumber = (phone) => {
    if (!phone) return phone;
    return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1-$2-$3');
};

const getDateFormatOptions = (format) => {
    switch (format) {
        case 'yyyy-MM-dd':
            return { year: 'numeric', month: '2-digit', day: '2-digit' };
        case 'yyyy/MM/dd HH:mm:ss':
            return { 
                year: 'numeric', 
                month: '2-digit', 
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            };
        default:
            return {};
    }
};

const getNumberFormatOptions = (format) => {
    if (format.includes('%')) {
        return { style: 'percent', minimumFractionDigits: 2 };
    }
    if (format.includes('¥')) {
        return { style: 'currency', currency: 'CNY' };
    }
    return { minimumFractionDigits: 0, maximumFractionDigits: 2 };
};

/**
 * 数据览对话框组件
 * @param {Object} props - 组件属性
 * @param {boolean} props.open - 对话框是否显示
 * @param {Function} props.onClose - 关闭对话框的回调函数
 * @param {Array} props.data - 要显示的数据数组
 * @param {Object} props.config - 当前配置信息
 * @param {Function} props.onExport - 导出数据的回调函数
 */
const DataPreviewDialog = ({ open, onClose, data, config, onExport }) => {
    const [exportFormat, setExportFormat] = useState('csv');
    const [exportTarget, setExportTarget] = useState('file');
    
    // 数据库配置状态
    const [dbConfigOpen, setDbConfigOpen] = useState(false);
    const [dbConfig, setDbConfig] = useState({
        host: '',
        port: '',
        database: '',
        table: '',
        username: '',
        password: ''
    });
    
    // Kafka配置状态
    const [kafkaConfigOpen, setKafkaConfigOpen] = useState(false);
    const [kafkaConfig, setKafkaConfig] = useState({
        brokers: '',
        topic: '',
        key: ''
    });

    // 分页状态
    const [page, setPage] = useState(0);
    const [rowsPerPage, setRowsPerPage] = useState(10);
    
    // 搜索状态
    const [searchText, setSearchText] = useState('');
    
    // 排序状态
    const [orderBy, setOrderBy] = useState('');
    const [order, setOrder] = useState('asc');
    
    // 导出进度状态
    const [exporting, setExporting] = useState(false);

    const [snackbar, setSnackbar] = useState({
        open: false,
        message: '',
        severity: 'success'
    });

    // 处理搜索
    const filteredData = useMemo(() => {
        if (!searchText) return data;
        
        return data.filter(item => 
            Object.entries(item).some(([key, value]) => {
                const field = config?.fields?.find(f => f.fieldName === key);
                const formattedValue = formatValue(value, field?.fieldType, field?.format);
                return String(formattedValue)
                    .toLowerCase()
                    .includes(searchText.toLowerCase());
            })
        );
    }, [data, searchText, config]);

    // 处理排序
    const sortedData = useMemo(() => {
        if (!orderBy) return filteredData;
        
        return [...filteredData].sort((a, b) => {
            const aValue = a[orderBy];
            const bValue = b[orderBy];
            
            if (order === 'asc') {
                return aValue < bValue ? -1 : 1;
            } else {
                return bValue < aValue ? -1 : 1;
            }
        });
    }, [filteredData, orderBy, order]);

    // 处理分页数据
    const paginatedData = sortedData.slice(
        page * rowsPerPage,
        page * rowsPerPage + rowsPerPage
    );

    // 处理排序化
    const handleSort = (field) => {
        const isAsc = orderBy === field && order === 'asc';
        setOrder(isAsc ? 'desc' : 'asc');
        setOrderBy(field);
    };

    // 处理分页变化
    const handleChangePage = (event, newPage) => {
        setPage(newPage);
    };

    const handleChangeRowsPerPage = (event) => {
        setRowsPerPage(parseInt(event.target.value, 10));
        setPage(0);
    };

    // 处理导出
    const handleExport = async () => {
        setExporting(true);
        try {
            if (exportTarget === 'kafka') {
                const response = await configurationApi.exportToKafka(config.id, {
                    topic: kafkaConfig.topic,
                    key: kafkaConfig.key,
                    brokers: kafkaConfig.brokers
                });
                
                if (response.data.success) {
                    setSnackbar({
                        open: true,
                        message: `数据导出成功！总数：${response.data.totalCount}, 成功：${response.data.successCount}`,
                        severity: 'success'
                    });
                    onClose();
                } else {
                    throw new Error('导出失败');
                }
            } else if (exportTarget === 'file') {
                await onExport(exportFormat);
            } else if (exportTarget === 'mysql') {
                await onExport('mysql', dbConfig);
            }
        } catch (error) {
            setSnackbar({
                open: true,
                message: `导出失败：${error.message || '未知错误'}`,
                severity: 'error'
            });
        } finally {
            setExporting(false);
        }
    };

    return (
        <Dialog 
            open={open} 
            onClose={onClose} 
            maxWidth="md" 
            fullWidth
        >
            {/* 对话框标题 */}
            <DialogTitle>生成的数据预览</DialogTitle>

            {/* 对话框内容：数据表格 */}
            <DialogContent>
                {/* 搜索框 */}
                <Box sx={{ mb: 2 }}>
                    <TextField
                        fullWidth
                        size="small"
                        placeholder="搜索..."
                        value={searchText}
                        onChange={(e) => setSearchText(e.target.value)}
                        InputProps={{
                            startAdornment: (
                                <InputAdornment position="start">
                                    <SearchIcon />
                                </InputAdornment>
                            )
                        }}
                    />
                </Box>

                <TableContainer component={Paper}>
                    <Table size="small">
                        <TableHead>
                            <TableRow>
                                <TableCell>序号</TableCell>
                                {data[0] && Object.keys(data[0]).map((key) => (
                                    <TableCell key={key}>
                                        <TableSortLabel
                                            active={orderBy === key}
                                            direction={orderBy === key ? order : 'asc'}
                                            onClick={() => handleSort(key)}
                                        >
                                            {key}
                                        </TableSortLabel>
                                    </TableCell>
                                ))}
                            </TableRow>
                        </TableHead>
                        <TableBody>
                            {paginatedData.map((item, index) => (
                                <TableRow key={index}>
                                    <TableCell>{page * rowsPerPage + index + 1}</TableCell>
                                    {Object.entries(item).map(([key, value], i) => {
                                        const field = config?.fields?.find(f => f.fieldName === key);
                                        return (
                                            <TableCell key={i}>
                                                {formatValue(value, field?.fieldType, field?.format)}
                                            </TableCell>
                                        );
                                    })}
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </TableContainer>

                {/* 分页控件 */}
                <TablePagination
                    component="div"
                    count={filteredData.length}
                    page={page}
                    onPageChange={handleChangePage}
                    rowsPerPage={rowsPerPage}
                    onRowsPerPageChange={handleChangeRowsPerPage}
                    rowsPerPageOptions={[10, 25, 50, 100]}
                    labelRowsPerPage="每页行数"
                    labelDisplayedRows={({ from, to, count }) => 
                        `${from}-${to} 共 ${count} 条`
                    }
                />
            </DialogContent>

            {/* 对话框底部按钮 */}
            <DialogActions>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, flexGrow: 1 }}>
                    <FormControl size="small">
                        <InputLabel>导出目标</InputLabel>
                        <Select
                            value={exportTarget}
                            label="导出目标"
                            onChange={(e) => setExportTarget(e.target.value)}
                            style={{ minWidth: 120 }}
                        >
                            <MenuItem value="file">文件</MenuItem>
                            <MenuItem value="mysql">MySQL</MenuItem>
                            <MenuItem value="kafka">Kafka</MenuItem>
                        </Select>
                    </FormControl>

                    {exportTarget === 'file' && (
                        <FormControl size="small">
                            <InputLabel>文件格式</InputLabel>
                            <Select
                                value={exportFormat}
                                label="文件格式"
                                onChange={(e) => setExportFormat(e.target.value)}
                            >
                                <MenuItem value="csv">CSV</MenuItem>
                                <MenuItem value="json">JSON</MenuItem>
                            </Select>
                        </FormControl>
                    )}

                    {exportTarget === 'mysql' && (
                        <Button
                            onClick={() => setDbConfigOpen(true)}
                            variant="outlined"
                            size="small"
                        >
                            配置数据库
                        </Button>
                    )}

                    {exportTarget === 'kafka' && (
                        <Button
                            onClick={() => setKafkaConfigOpen(true)}
                            variant="outlined"
                            size="small"
                        >
                            配置Kafka
                        </Button>
                    )}
                </Box>
                
                {exporting && (
                    <Box sx={{ width: '100%', position: 'absolute', top: 0, left: 0 }}>
                        <LinearProgress />
                    </Box>
                )}
                
                <Button 
                    onClick={handleExport} 
                    color="primary"
                    disabled={exporting}
                >
                    {exporting ? '导出中...' : '导出数据'}
                </Button>
                <Button onClick={onClose} color="primary">
                    关闭
                </Button>
            </DialogActions>

            {/* MySQL配置对话框 */}
            <Dialog open={dbConfigOpen} onClose={() => setDbConfigOpen(false)}>
                <DialogTitle>MySQL配置</DialogTitle>
                <DialogContent>
                    <Grid container spacing={2}>
                        <Grid item xs={12} md={6}>
                            <TextField
                                label="主机地址"
                                value={dbConfig.host}
                                onChange={(e) => setDbConfig({...dbConfig, host: e.target.value})}
                                fullWidth
                            />
                        </Grid>
                        <Grid item xs={12} md={6}>
                            <TextField
                                label="端口"
                                value={dbConfig.port}
                                onChange={(e) => setDbConfig({...dbConfig, port: e.target.value})}
                                fullWidth
                            />
                        </Grid>
                        <Grid item xs={12} md={6}>
                            <TextField
                                label="数据库名"
                                value={dbConfig.database}
                                onChange={(e) => setDbConfig({...dbConfig, database: e.target.value})}
                                fullWidth
                            />
                        </Grid>
                        <Grid item xs={12} md={6}>
                            <TextField
                                label="表名"
                                value={dbConfig.table}
                                onChange={(e) => setDbConfig({...dbConfig, table: e.target.value})}
                                fullWidth
                            />
                        </Grid>
                        <Grid item xs={12} md={6}>
                            <TextField
                                label="用户名"
                                value={dbConfig.username}
                                onChange={(e) => setDbConfig({...dbConfig, username: e.target.value})}
                                fullWidth
                            />
                        </Grid>
                        <Grid item xs={12} md={6}>
                            <TextField
                                label="密码"
                                type="password"
                                value={dbConfig.password}
                                onChange={(e) => setDbConfig({...dbConfig, password: e.target.value})}
                                fullWidth
                            />
                        </Grid>
                    </Grid>
                </DialogContent>
                <DialogActions>
                    <Button onClick={() => setDbConfigOpen(false)}>取消</Button>
                    <Button onClick={() => setDbConfigOpen(false)} color="primary">
                        确定
                    </Button>
                </DialogActions>
            </Dialog>

            {/* Kafka配置对话框 */}
            <Dialog open={kafkaConfigOpen} onClose={() => setKafkaConfigOpen(false)}>
                <DialogTitle>Kafka配置</DialogTitle>
                <DialogContent>
                    <Grid container spacing={2}>
                        <Grid item xs={12}>
                            <TextField
                                label="Broker列表"
                                value={kafkaConfig.brokers}
                                onChange={(e) => setKafkaConfig({...kafkaConfig, brokers: e.target.value})}
                                fullWidth
                                helperText="多个broker用逗号分隔"
                            />
                        </Grid>
                        <Grid item xs={12}>
                            <TextField
                                label="Topic"
                                value={kafkaConfig.topic}
                                onChange={(e) => setKafkaConfig({...kafkaConfig, topic: e.target.value})}
                                fullWidth
                            />
                        </Grid>
                        <Grid item xs={12}>
                            <TextField
                                label="Key"
                                value={kafkaConfig.key}
                                onChange={(e) => setKafkaConfig({...kafkaConfig, key: e.target.value})}
                                fullWidth
                                helperText="可选"
                            />
                        </Grid>
                    </Grid>
                </DialogContent>
                <DialogActions>
                    <Button onClick={() => setKafkaConfigOpen(false)}>取消</Button>
                    <Button onClick={() => setKafkaConfigOpen(false)} color="primary">
                        确定
                    </Button>
                </DialogActions>
            </Dialog>

            <Snackbar
                open={snackbar.open}
                autoHideDuration={6000}
                onClose={() => setSnackbar({ ...snackbar, open: false })}
            >
                <Alert severity={snackbar.severity} onClose={() => setSnackbar({ ...snackbar, open: false })}>
                    {snackbar.message}
                </Alert>
            </Snackbar>
        </Dialog>
    );
};

export default DataPreviewDialog; 